package udp_tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) {
        // 指定服务器监听的端口
        int port = 12345;

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("TCP服务器已启动，等待客户端连接...");

            // 接受客户端连接
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端已连接: " + clientSocket.getInetAddress().getHostAddress());

            // 获取输入流和输出流
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(
                    clientSocket.getOutputStream(), true);

            // 接收客户端消息
            String clientMessage = in.readLine();
            System.out.println("收到客户端消息: " + clientMessage);

            // 发送响应
            String response = "服务器已收到你的消息: " + clientMessage;
            out.println(response);
            System.out.println("已发送响应: " + response);

            // 关闭连接
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}